import React, { useState, useRef, useEffect } from 'react';
import { Layout, Select, Avatar, Button } from '@arco-design/web-react';
import { IconUser, IconPoweroff, IconDown } from '@arco-design/web-react/icon';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../../hooks/useLanguage';
import { useAuth } from '../../hooks/useAuth';
import logo from '../../assets/logo.png';
import './Header.css';

const HeaderLayout = Layout.Header;
const Option = Select.Option;

/**
 * Header组件
 * 应用程序顶部导航栏，包含Logo、标题、语言选择、用户登录状态显示
 * 
 * @returns {React.FC} Header组件
 * @author ltx
 * @date 2024-12-19
 */
const Header: React.FC = () => {
  // 语言Hook
  const { language, changeLanguage } = useLanguage();
  // 路由导航Hook
  const navigate = useNavigate();
  // 用户认证Hook
  const { user, isLoggedIn, loading, logout } = useAuth();
  
  // 添加调试日志
  console.log('Header组件渲染 - 用户状态:', { user, isLoggedIn, loading });
  // 下拉菜单显示状态
  const [dropdownVisible, setDropdownVisible] = useState<boolean>(false);
  // 下拉菜单引用
  const dropdownRef = useRef<HTMLDivElement>(null);

  /**
   * 处理登录按钮点击事件
   * 跳转到登录页面
   * 
   * @returns {void} 无返回值
   */
  const handleLoginClick = (): void => {
    navigate('/login');
  };

  /**
   * 处理退出登录
   * 调用logout方法并立即关闭下拉菜单，确保UI能正确响应状态变化
   * 
   * @returns {Promise<void>} 无返回值的Promise
   * @author ltx
   * @since 2025-01-27 16:00:00
   */
  const handleLogout = async (): Promise<void> => {
    console.log('🎯 Header组件：开始处理退出登录...');
    
    // 立即关闭下拉菜单
    setDropdownVisible(false);
    
    // 调用useAuth提供的logout方法（已经优化过，不会抛出错误）
    await logout();
    
    console.log('✅ Header组件：退出登录处理完成');
  };

  /**
   * 切换下拉菜单显示状态
   * 
   * @returns {void} 无返回值
   */
  const toggleDropdown = (): void => {
    setDropdownVisible(!dropdownVisible);
  };

  /**
   * 处理点击外部区域关闭下拉菜单
   * 
   * @param {MouseEvent} event - 鼠标点击事件
   * @returns {void} 无返回值
   */
  const handleClickOutside = (event: MouseEvent): void => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
      setDropdownVisible(false);
    }
  };

  /**
   * 组件挂载时添加点击外部事件监听
   * 组件卸载时移除事件监听
   */
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  /**
   * 处理个人资料点击事件
   * 
   * @returns {void} 无返回值
   */
  const handleProfileClick = (): void => {
    console.log('📝 处理个人资料点击');
    // 跳转到用户资料页面
    navigate('/profile');
    // 关闭下拉菜单
    setDropdownVisible(false);
  };

  /**
   * 直接处理退出登录点击事件
   * 
   * @param {React.MouseEvent} event - 鼠标点击事件
   * @returns {void} 无返回值
   */
  const handleLogoutClick = (event: React.MouseEvent): void => {
    console.log('🎯 直接点击退出登录按钮');
    event.preventDefault();
    event.stopPropagation();
    // 关闭下拉菜单
    setDropdownVisible(false);
    // 执行退出登录
    handleLogout();
  };

  /**
   * 创建用户下拉菜单（使用简单div实现）
   * 
   * @returns {React.ReactNode} 下拉菜单内容
   */
  const renderUserMenu = (): React.ReactNode => (
    <div className="simple-dropdown-menu">
      <div className="dropdown-item" onClick={handleProfileClick}>
        <IconUser style={{ marginRight: 8 }} />
        个人资料
      </div>
      <div className="dropdown-divider"></div>
      <div className="dropdown-item logout-item" onClick={handleLogoutClick}>
        <IconPoweroff style={{ marginRight: 8 }} />
        退出登录
      </div>
    </div>
  );

  /**
   * 渲染用户信息区域
   * 根据登录状态显示不同的UI
   * 
   * @returns {React.ReactNode} 用户信息区域内容
   */
  const renderUserArea = (): React.ReactNode => {
    if (loading) {
      return (
        <Button loading size="small">
          加载中...
        </Button>
      );
    }

    if (isLoggedIn && user) {
      return (
        <div className="user-info" ref={dropdownRef}>
          <div 
            className="user-profile" 
            onClick={toggleDropdown}
          >
            <Avatar size={28} style={{ backgroundColor: '#165DFF' }}>
              {user.realName ? user.realName.charAt(0) : user.username.charAt(0)}
            </Avatar>
            <span className="username">
              {user.realName || user.username}
            </span>
            <IconDown className={`dropdown-icon ${dropdownVisible ? 'rotated' : ''}`} />
          </div>
          
          <div className={`simple-dropdown ${dropdownVisible ? 'show' : ''}`}>
            {renderUserMenu()}
          </div>
        </div>
      );
    }

    return (
      <button className="custom-login-button" onClick={handleLoginClick}>
        <span>登录</span>
      </button>
    );
  };

  return (
    <HeaderLayout className="app-header">
      <div className="header-content">
        <div className="header-left">
          <img src={logo} alt="Logo" className="app-logo" />
          <h1 className="app-title">Bug Seeker</h1>
        </div>
        <div className="header-actions">
          <Select
            value={language}
            onChange={changeLanguage}
            style={{ width: 120, marginRight: 20 }}
            size="default"
          >
            <Option value="zh-CN">中文</Option>
            <Option value="en-US">English</Option>
          </Select>
          {renderUserArea()}
        </div>
      </div>
    </HeaderLayout>
  );
};

export default Header;